package com.beauty.controller;

import com.beauty.dto.BeautyResponse;
import com.beauty.dto.ResponseList;
import com.beauty.dto.note.DeleteNoteData;
import com.beauty.dto.note.GetNoteDetailRes;
import com.beauty.dto.note.GetNoteListRes;
import com.beauty.dto.note.InsertNoteData;
import com.beauty.mapper.IImageNoteMapper;
import com.beauty.mapper.INoteMapper;
import com.beauty.mapper.IUserMapper;
import com.beauty.models.Note;
import com.beauty.services.MyBaitsHelp;
import org.apache.ibatis.jdbc.Null;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("api/note")
public class NoteController {
    private final MyBaitsHelp myBaitsHelp;

    NoteController(MyBaitsHelp myBaitsHelp) {
        this.myBaitsHelp = myBaitsHelp;
    }

    /**
     * 获得全部Note
     *
     * @param pageSize
     * @param pageIndex
     * @param searchTerm
     * @return
     */
    @GetMapping("/getNoteList")
    public BeautyResponse<ResponseList<GetNoteListRes>> getNoteList(@RequestParam(defaultValue = "1") int pageIndex,
                                                                    @RequestParam(defaultValue = "10") int pageSize,
                                                                    @RequestParam(defaultValue = "") String title,
                                                                    @RequestParam(defaultValue = "") String userId) {

        var res = new BeautyResponse<ResponseList<GetNoteListRes>>();
        res.response = new ResponseList();
        List<GetNoteListRes> noteList = new ArrayList<>();
        // 开始操作数据库
        try (var session = myBaitsHelp.factory.openSession()) {
            List<Note> list = new ArrayList();
            if (userId != null & !userId.isEmpty()) {
                list = session.getMapper(INoteMapper.class).selectNoteListByUserId((pageIndex - 1) * pageSize, pageSize, userId);
                res.response.count = session.getMapper(INoteMapper.class).selectNoteListCount(null, userId);
            } else {
                list = session.getMapper(INoteMapper.class).selectNoteList((pageIndex - 1) * pageSize, title, pageSize);
                res.response.count = session.getMapper(INoteMapper.class).selectNoteListCount(title, null);
            }

            list.forEach(n -> {
                var note = new GetNoteListRes();
                var user = session.getMapper(IUserMapper.class).selectUserById(n.userId);
                var images = session.getMapper(IImageNoteMapper.class).selectImagesByNoteId(n.id);
                note.id = n.id;
                note.title = n.title;
                note.content = n.content;
                note.favorite = n.favorite;
                note.createDate = n.createDate;
                if (user != null) {
                    note.user.name = user.name;
                    note.user.avatar = user.avatar;
                }
                if (images.size() != 0) {
                    note.image = images.stream().findFirst().get().url;
                }
                noteList.add(note);
            });
            res.response.data = noteList;
        }

        return res;
    }

    /**
     * 插入Note
     *
     * @param note
     * @return
     */
    @PostMapping("/insertNote")
    public BeautyResponse insertNote(@RequestBody() InsertNoteData note, @CookieValue(name = "userId") String userId) {
        List<Note> noteList;
        var createNote = new Note();
        var res = new BeautyResponse<Null>();
        createNote.title = note.title;
        createNote.content = note.content;
        createNote.id = UUID.randomUUID().toString();
        createNote.createDate = new Date().getTime();

        // 开始操作数据库
        try (var session = myBaitsHelp.factory.openSession()) {
            session.getMapper(INoteMapper.class).insertNote(createNote.id, createNote.title, createNote.content, createNote.createDate, userId, 0);
            note.images.forEach(i -> {
                session.getMapper(IImageNoteMapper.class).insertImages(UUID.randomUUID().toString(), i, createNote.createDate, createNote.id);
            });
        } catch (Error e) {
            res.message = e.getMessage();
            res.status = HttpStatus.INTERNAL_SERVER_ERROR.value();
            return res;
        }
        res.message = "插入成功";
        return res;
    }


    /**
     * 获得单个笔记内容
     *
     * @param id
     * @return
     */
    @GetMapping("/getNoteDetail")
    public BeautyResponse<GetNoteDetailRes> getNoteDetail(@RequestParam(defaultValue = "") String id) {
        var res = new BeautyResponse<GetNoteDetailRes>();
        res.response = new GetNoteDetailRes();
        try (var session = myBaitsHelp.factory.openSession()) {
            var note = session.getMapper(INoteMapper.class).selectNote(id);
            res.response.content = note.content;
            res.response.userId = note.userId;
            res.response.id = note.id;
            res.response.title = note.title;
            res.response.createDate = note.createDate;
            res.response.favorite = note.favorite;
            var imgs = session.getMapper(IImageNoteMapper.class).selectImagesByNoteId(id);
            if (imgs != null && imgs.size() != 0) {
                res.response.imgs = imgs.stream().map(i -> i.url).toList();
            }
        } catch (Error e) {
            res.message = e.getMessage();
            res.status = HttpStatus.INTERNAL_SERVER_ERROR.value();
            return res;
        }
        return res;
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @PostMapping("/deleteNote")
    public BeautyResponse<String> deleteNote(@RequestBody() DeleteNoteData data) {
        var res = new BeautyResponse<String>();
        try (var session = myBaitsHelp.factory.openSession()) {
            session.getMapper(INoteMapper.class).deleteNote(data.id);
            res.message = "删除成功";
        } catch (Error e) {
            res.message = e.getMessage();
            res.status = HttpStatus.INTERNAL_SERVER_ERROR.value();
        }
        return res;
    }

}
